package examples;

import com.oracle.coherence.patterns.security.KerberosTicketDecoder;
import com.oracle.coherence.patterns.security.KrbSecurityHelper;
import com.oracle.coherence.patterns.security.SystemPropertyLoader;
import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
import org.ietf.jgss.GSSContext;
import org.ietf.jgss.GSSCredential;
import org.ietf.jgss.GSSManager;

import javax.security.auth.Subject;
import javax.security.auth.login.LoginContext;
import java.io.FileReader;
import java.security.PrivilegedExceptionAction;

/**
 * @author Jonathan Knight
 */
public class KrbServer implements PrivilegedExceptionAction<Object> {

    public static void main(String[] args) throws Exception {
        if (System.getProperties().containsKey(SystemPropertyLoader.MARKER_ENVIRONMENT)) {
            SystemPropertyLoader.loadProperties(null);
        }

        LoginContext lc = new LoginContext("Coherence");
        lc.login();
        Subject subject = lc.getSubject();
        Subject.doAs(subject, new KrbServer());
    }

    @Override
    public Object run() throws Exception {
        StringBuilder ticket = new StringBuilder();
        FileReader reader = new FileReader("ticket.txt");
        int c = reader.read();
        while (c >= 0) {
            ticket.append((char)c);
            c = reader.read();
        }

        byte[] token = Base64.decode(ticket.toString());
        Subject subject = KrbSecurityHelper.getCurrentSubject();
        KerberosTicketDecoder decoder = new KerberosTicketDecoder(token, subject);
        decoder.getClientPrincipalName();
        
        GSSManager manager = GSSManager.getInstance();
        GSSContext context = manager.createContext((GSSCredential) null);
        context.acceptSecContext(token, 0, token.length);

        //System.out.println("Context Established: " + context.isEstablished());
        return null;
    }


}
